package com.lst.servlet;

import java.awt.image.BufferedImage;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.druid.util.StringUtils;
import com.github.miemiedev.mybatis.paginator.domain.PageBounds;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.lst.base.entity.BaseRequest;
import com.lst.base.entity.BaseResponse;
import com.lst.common.CommCode;
import com.lst.entity.request.ClientDetailReqPara;
import com.lst.entity.response.ClientDetailResPara;
import com.lst.model.Dynamic;
import com.lst.model.Focus;
import com.lst.model.JiluLog;
import com.lst.model.MstClient;
import com.lst.model.MstDiscuss;
import com.lst.model.OnlineCourse;
import com.lst.model.SportRecords;
import com.lst.service.ClientNumService;
import com.lst.service.CompanionService;
import com.lst.service.DynamicService;
import com.lst.service.FocusService;
import com.lst.service.JiluLogService;
import com.lst.service.MstClientService;
import com.lst.service.MstDiscussService;
import com.lst.service.OnlineCourseService;
import com.lst.service.PlanService;
import com.lst.service.SportRecordsService;
import com.lst.utils.CommFunUtils;
import com.lst.utils.RequestUtils;

public class ClientDetailServlet extends BaseServlet {

	private static final long serialVersionUID = 1L;

	private MstClientService mstClientService = ctx.getBean(MstClientService.class); 
	
    private FocusService focusService = ctx.getBean(FocusService.class);
	
	private DynamicService dynamicService = ctx.getBean(DynamicService.class);
	
	private CompanionService companionService = ctx.getBean(CompanionService.class);
	
	private SportRecordsService sportRecordsService = ctx.getBean(SportRecordsService.class);
	
    private PlanService planService = ctx.getBean(PlanService.class);
	
	private OnlineCourseService onlineCourseService = ctx.getBean(OnlineCourseService.class);
	
	private JiluLogService jiluLogService = ctx.getBean(JiluLogService.class);
	
	private MstDiscussService mstDiscussService = ctx.getBean(MstDiscussService.class);
	
	private ClientNumService clientNumService = ctx.getBean(ClientNumService.class);
	

	
	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) {
		doPost(request, response);
	}
	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) {
		
		ClientDetailResPara resPara = new ClientDetailResPara();

		try {
			ClientDetailReqPara reqPara = getReqPara(request);
		
		if(isCheckField(reqPara,resPara)){
			Integer userid = Integer.valueOf(reqPara.getUserid());
			Integer friendId = Integer.valueOf(reqPara.getFriendId());
			
			Integer page = Integer.valueOf(reqPara.getPage());
			Integer pagesize = Integer.valueOf(reqPara.getPagesize());
			
			//关注数量
			int totalNum=focusService.countFocusTotal(friendId);
			//粉丝数量
			int totalFansNum=focusService.countFansTotal(friendId);
			//动态数量
			int dynamicTotalNum=dynamicService.countTotal(friendId);
			//标识是否关注此人
			Map<String, Object> map = new HashMap<String, Object>();		
			map.put("createUser", userid);
			map.put("focusUser", friendId);
			map.put("isDelete", false);
			Focus focus=focusService.selectByMap(map);
			if(focus!=null){
				resPara.setIsFocus(true);
			}
			
			//查询对象信息
			MstClient client=mstClientService.selectByPrimaryKey(friendId);
		
			client.setPortrait(client.getReserved11());
			
			//查询动态
			Map<String, Object> reqMap = new HashMap<String, Object>();		
			reqMap.put("isDeleted", false);
			reqMap.put("createUser", friendId);
			reqMap.put("orderByClause", "md.createdate desc");
			PageBounds pageBounds = new PageBounds(page,pagesize);
			List<Dynamic> dynamicList=dynamicService.queryByList2(reqMap, pageBounds);
			if(dynamicList!=null&&dynamicList.size()>0){
               for(Dynamic dynamic:dynamicList){
            	   
					String pictureUrl=dynamic.getDynamicUrl();
					if(pictureUrl!=null){
						String pictureUrl2=pictureUrl.split(",")[0];
						dynamic.setDynamicUrl(pictureUrl2);
						
						int[] widths = new int[1];
						int[] heights = new int[1];

							InputStream is = null;
							BufferedImage src = null;
							try {
								is = new FileInputStream(CommCode.readUrl + pictureUrl2.substring(13));
								src = javax.imageio.ImageIO.read(is);
								widths[0] = src.getWidth(); // 得到源图宽
								heights[0] = src.getHeight(); // 得到源图高
								is.close();
							} catch (Exception e) {
								e.printStackTrace();
							}

							dynamic.setWidth(widths);
							dynamic.setHeight(heights);
					}
					
					Map<String, Object> dymap = new HashMap<String, Object>();
					dymap.put("enabled", true);
					dymap.put("isDeleted", false);
					dymap.put("tarid",dynamic.getDynamicId() );
					dymap.put("type", CommCode.SYSTEM_CARESEL_RANGE_DYNAMIC);
		            //评论数量
					Integer discussNum = mstDiscussService.queryCountByMap(dymap);
		            dynamic.setDiscussNum(discussNum);
		            
					 //喜欢数量
					Map<String, Object> mapjl = new HashMap<String, Object>();
			        mapjl.put("sourceId", dynamic.getDynamicId());
			        mapjl.put("jiluType", 1);
					int loveNum=jiluLogService.countBySourceId(mapjl);
					dynamic.setLoveNum(loveNum);
					
					//喜欢标识
					Map<String, Object> jilumap = new HashMap<String, Object>();
					jilumap.put("jiluType", 1);
					jilumap.put("isDelete", false);
					jilumap.put("sourceId", dynamic.getDynamicId());
					jilumap.put("createUser", userid);
					JiluLog jilu=jiluLogService.queryByMap(jilumap);
					if(jilu!=null){
						dynamic.setIsLove(jilu.getIsLove());
					}else{
						dynamic.setIsLove(false);
					}
					
					//标识是否收藏
					Map<String, Object> fmap = new HashMap<String, Object>();
					fmap.put("enabled", true);
					fmap.put("isdeleted", false);
					fmap.put("clientid", userid);
					fmap.put("actid", dynamic.getDynamicId());
					fmap.put("acttype", CommCode.SYSTEM_CARESEL_RANGE_DYNAMIC);
					fmap.put("numtype", CommCode.SYSTEM_COUNT_FAVORITE);
					Integer count = clientNumService.queryCountByMap(fmap);
					if(count>0){
						dynamic.setIsFavorite(true);
					}else{
						dynamic.setIsFavorite(false);
					}
				
				}
				
				resPara.setDynamic(dynamicList);
			}
			
			//查询发布的结伴数量
			int comNum=companionService.countByKey(friendId);
			resPara.setCompanionTotalNum(comNum);
			
			//统计训练总次数
			Integer trainTotalNum=sportRecordsService.countByUser(friendId);
			resPara.setTrainTotalNum(trainTotalNum);
			//勋章数量统计
			int achievementTotalNum=0;
			//首次型勋章
			
			int planNum=planService.countByUser(friendId);
			if(planNum>=1){
				achievementTotalNum++;
			}
			if(planNum>=4){
				achievementTotalNum++;
			}
			if(planNum>=16){
				achievementTotalNum++;
			}
			
			//专注勋章
			List<SportRecords> sportList=sportRecordsService.countByUser4(friendId);
			int num1=0;
			int num2=0;
			int num3=0;
			
			//连续型勋章
			Boolean lxNum7=false;    //连续训练7天
			Boolean lxNum21=false;    //连续训练21天
			Boolean lxNum100=false;  //连续训练100天
			Boolean lxNum365=false;  //连续训练100天
			
			if(sportList!=null&&sportList.size()>0){
				for(SportRecords sportRecords:sportList){
					OnlineCourse onlineCourse=onlineCourseService.selectByPrimaryKey(sportRecords.getCourseId());
					int num=onlineCourse.getKfClassType();
					if(num==389){
						num1++;
					}
					if(num==390){
						num2++;
					}
					if(num==391){
						num3++;
					}
					
					int lxNum=sportRecords.getTotalNum();
					if(lxNum>=7){
						lxNum7=true;
					}
					if(lxNum>=21){
						lxNum21=true;
					}
					if(lxNum>=100){
						lxNum100=true;
					}
					if(lxNum>=365){
						lxNum365=true;
					}
					
				}
				if(num1>=5){
					achievementTotalNum++;
				}
				if(num2>=5){
					achievementTotalNum++;
				}
				if(num3>=5){
					achievementTotalNum++;
				}
				
				if(lxNum7==true){
					achievementTotalNum++;
				}
				if(lxNum21==true){
					achievementTotalNum++;
				}
				if(lxNum100==true){
					achievementTotalNum++;
				}
				if(lxNum365==true){
					achievementTotalNum++;
				}
			}
			
			//获得1万粉丝关注勋章
			int totalFansNum2=focusService.countFansTotal(userid);
			if(totalFansNum2>=10000){
				achievementTotalNum++;
			}
			
			//麒麟才子勋章，获得赞超过一千
			Map<String, Object> dymap = new HashMap<String, Object>();
			dymap.put("enabled", true);
			dymap.put("isDeleted", false);
			dymap.put("userid",userid);
			List<MstDiscuss> mstDiscussList=mstDiscussService.queryListByMap(dymap);
			if(mstDiscussList!=null&&mstDiscussList.size()>0){
				for(MstDiscuss mstDiscuss:mstDiscussList){
					//点赞量
					Integer praisenum = CommFunUtils.opNum(null, mstDiscuss.getId(), CommCode.SYSTEM_CARESEL_RANGE_DISCUSS, CommCode.SYSTEM_COUNT_PRAISE, clientNumService);
					if(praisenum>=1000){
					   achievementTotalNum++;
					   break;
					}
				}
			}

			resPara.setAchievementTotalNum(achievementTotalNum);
			
			resPara.setDynamicTotalNum(dynamicTotalNum);
			resPara.setTotalNum(totalNum);
			resPara.setTotalFansNum(totalFansNum);
			resPara.setMstClient(client);
			
			resPara.setCode(CommCode.M_Y000000);
			resPara.setMessage(CommCode.M_Y000001);
		  }
		} catch (Exception e) {
			resPara.setCode(CommCode.M_A000000);
			resPara.setMessage(CommCode.M_SYS0001);

			logger.error("doPost error: ", e);
		}
		
		try {
			response.setContentType("application/json;charset=utf-8");
			response.setHeader("pragma", "no-cache");
			response.setHeader("cache-control", "no-cache");

			Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").excludeFieldsWithoutExposeAnnotation().serializeNulls().create();
			String jsonResult = gson.toJson(resPara);
		//	logger.info("ClientDiscussServlet jsonResult:" + jsonResult);

			PrintWriter out = response.getWriter();
			out.print(jsonResult);
			out.flush();
			out.close();

		//	logger.info("doPost end run(s): " + DateUtil.calLastedTime(startDate));
		} catch (Exception e) {
			resPara.setCode(CommCode.M_A000000);
			resPara.setMessage(CommCode.M_SYS0003);

			logger.error("doPost error: ", e);
		}
	}

	@Override
	public ClientDetailReqPara getReqPara(HttpServletRequest request) {

		ClientDetailReqPara reqPara = null;

		try {
			BaseRequest baseRequest = RequestUtils.getRequestPara(request, new ClientDetailReqPara());

			reqPara = (ClientDetailReqPara) baseRequest.clone();

			String userid = request.getParameter("userid");
			String friendId = request.getParameter("friendId");
			String page = request.getParameter("page");
			String pagesize = request.getParameter("pagesize");
			
//			logger.info("reqPara userid:" + userid);
//			logger.info("reqPara friendId: " + friendId);
		
	        reqPara.setFriendId(friendId);
	        reqPara.setUserid(userid);
	        reqPara.setPagesize(pagesize);
	        reqPara.setPage(page);

		} catch (Exception e) {
			logger.error("getReqPara error: ", e);
		}

		return reqPara;
	}

	@Override
	public boolean isCheckField(BaseRequest reqPara, BaseResponse resPara) {
		boolean flag = false;

		BaseRequest cdReqPara = (BaseRequest) reqPara;
		BaseResponse cdResPara = (BaseResponse) resPara;

       if (StringUtils.isEmpty(cdReqPara.getUserid())) {
			cdResPara.setCode(CommCode.M_A000000);
			cdResPara.setMessage(CommCode.M_P000002);
		}else if (StringUtils.isEmpty(cdReqPara.getPage())){
			cdResPara.setCode(CommCode.M_A000000);
			cdResPara.setMessage(CommCode.M_P000009);
		} else if (StringUtils.isEmpty(cdReqPara.getPagesize())){
			cdResPara.setCode(CommCode.M_A000000);
			cdResPara.setMessage(CommCode.M_P000010);
		} else {
			flag = true;
		}

		return  flag;
	}
}
